//
//  HPOAuthViewController.swift
//  MyWeibo
//
//  Created by Apeng on 16/4/10.
//  Copyright © 2016年 Apengpeng. All rights reserved.
//

import UIKit
import SVProgressHUD


class HPOAuthViewController: UIViewController {

    
    let webView = UIWebView()
    
    // 替换根视图
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setWebViewNavBar()
        
        loadOAthData()
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        
        SVProgressHUD.dismiss()
    }
    // 加载授权页面
    private func loadOAthData() {
        
        // 使用授权的参数拼接url
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    
    
    // setWebViewNavBar
    private func setWebViewNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillData")
    }
    
    // 按钮的点击事件
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillData() {
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '1095785221@qq.com', document.getElementById('passwd').value = '0312yhp//' ")
    }
}
    
    
// 遵守协议
extension HPOAuthViewController: UIWebViewDelegate {
    //MARK: webView 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        
        // 开启指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        // 设置webView的标题
        let webViewTitle = webView.stringByEvaluatingJavaScriptFromString("document.title")
        title = webViewTitle
        SVProgressHUD.dismiss()
    }
    
    
    // 请求授权 获取code , 是否加载授权回调页
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlS = request.URL?.absoluteString ?? ""
        // 获取字符串中的code
        let flag = "code="
        if urlS.containsString(flag) {
            // 授权成功
            let range = urlS.rangeOfString(flag)!
            let code = urlS.substringFromIndex(range.endIndex)
//            getAccessTokenByCode(code) 通过单例来调用函数
            HPUserAccountViewModel.sharedUserAccountViewModel.getAccessTokenByCode(code, finished: { (isSuccess) -> () in
                
                if !isSuccess {
                    //登录失败
                    SVProgressHUD.showErrorWithStatus("登录失败")
                    return
                }
                //跳转控制器
//                UIApplication.sharedApplication().keyWindow?.rootViewController = HPWellcomeView()
                // 使用通知跳转,
                NSNotificationCenter.defaultCenter().postNotificationName(HPSwitchRootViewController, object: nil)
            })
            // 不加载授权回调页
            return false
        }
        
//        print("授权后的字符串",urlS)
        //为了授权成功后不在加载webView 的数据而是显示APP 的数据返回false
        return true
    }

}

